/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.manager;

import com.unice.miage.oobdoo.entity.Album;
import com.unice.miage.oobdoo.entity.Partage;
import com.unice.miage.oobdoo.entity.Utilisateur;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Jeremy Romano
 */
@Stateless
public class PartageManager {

    @PersistenceContext
    private EntityManager em;

    public Partage creerPartage(Utilisateur u, Album a) {
        Partage p = new Partage(u, a);
        em.persist(p);
        return p;
    }

    public void deletePartage(Partage p) {
        try {
            em.remove(em.merge(p));
        } catch (Exception ex) {
            System.err.println("PartageManager.deletePartage, exception=" + ex);
        }
    }

    public Partage getPartageById(int id) {
        return em.find(Partage.class, id);
    }

    public Partage getPartageByUtilisateurAndAlbum(Utilisateur u, Album a) {
        try {
            Query q = em.createQuery("select p from Partage p where p.utilisateur = :u and p.album = :a");
            q.setParameter("u", u);
            q.setParameter("a", a);
            return (Partage) q.getSingleResult();
        } catch (NoResultException ex) {
            return null;
        } catch (Exception ex) {
            System.err.println("PartageManager.getPartageByUtilisateurAndAlbum, exception=" + ex);
            return null;
        }

    }

    public Collection<Partage> getPartagesNotView(Utilisateur u)
    {
        try {
            Query q = em.createQuery(
                    "select p "
                    + "from Partage p "
                    + "left join p.utilisateur u "
                    + "where p.vue = :vue "
                    + "and u = :auteur "
                    );
            q.setParameter("vue", false);
            q.setParameter("auteur", u);

            return q.getResultList();
        } catch (NoResultException e) {
            return null;
        } catch (Exception e) {
            System.err.println("exception=" + e);
            return null;
        }
    }
    public Partage updateViewPartage(Partage p, boolean b)
    {
        p.setVue(b);
        em.merge(p);
        return p;
    }
}
